﻿using System;
using System.Windows.Forms;

namespace ASmile.Win.Forms
{
    public partial class FrmSelectGrid : FrmBaseModal
    {
        public FrmSelectGrid()
        {
            InitializeComponent();
        }

        public Func<string, ApiResultList<object>> GetDataSource;

        public object SelectedModel { get; private set; }

        private void FrmSelectGrid_Load(object sender, EventArgs e)
        {
            ucPageNav1.PageChangedEvent += UcPageNav_PageChangedEvent;
            dgv.MouseDoubleClick += Dgv_MouseDoubleClick;
        }

        private void Dgv_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            tsBtnSelected_Click(sender, e);
        }

        private void UcPageNav_PageChangedEvent(int pageNo, int pageSize, out int recordCount)
        {
            var r = GetDataSource(tsTxtSearch.Text);
            dgv.DataSource = r.data;
            recordCount = r.count;
        }

        private void tsBtnSelected_Click(object sender, EventArgs e)
        {
            SelectedModel = dgv.GetSelectedItemData();
            if (SelectedModel == null)
            {
                ShowMessage("没有选中记录");
                return;
            }
            this.DialogResult = DialogResult.OK;
        }

        private void tsbtnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void tsBtnSearch_Click(object sender, EventArgs e)
        {
            UcPageNav_PageChangedEvent(1, ucPageNav1.OnePageCount, out int recordCount);
            ucPageNav1.InitiControl(recordCount);
        }

        private void tsTxtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                tsBtnSearch_Click(sender, e);
            }
        }
    }
}
